<?php
set_include_path($_SERVER['DOCUMENT_ROOT']);
include 'admin/includes/functions/admin-functions.php';
global $HTTP_HOST, $SMARTY,$DBobject;

$error = "登陆状态已经过期，请刷新重试。";
if (checkToken('admin', $_POST["formToken"]) && !empty($_POST['action'])) {
    switch ($_POST['action']) {
        case 'login':
            $result = AdminLogIn($_POST['email'], $_POST['password']);
            $error = ($result===true)?'':$result;
            $redirect = empty($_POST['redirect'])?'/admin/home':$_POST['redirect'];
            $_SESSION['redirect'] = '';
            break;
                
        case 'resetPassword':
            $error = "Sorry, '{$_POST['email']}' does not appear to be registered with this site. Check your email address or please create an account.";
            $sql = "SELECT * FROM tbl_admin WHERE admin_username = :uname AND admin_deleted IS NULL";
            if ($res  = $DBobject->wrappedSql($sql, array( ":uname" => $_POST['email'] ))) {
                $newPass = genRandomString(10);
                $temp_str = getPass($_POST['email'], $newPass);
                
                $params = array (
                        ":id" => $res[0]['admin_id'],
                        ":password" => $temp_str
                );
                $sql = "UPDATE tbl_admin SET admin_password = :password, admin_modified = now()	WHERE admin_id = :id ";
                if ($DBobject->wrappedSql($sql, $params)) {
                    try {
                        // SEND CONFIRMATION EMAIL
                        $SMARTY->assign("user_gname", $res[0]['admin_name']);
                        $SMARTY->assign("newPass", $newPass);
                        $SMARTY->assign('DOMAIN', "http://" . $HTTP_HOST);
                        $COMP = json_encode($CONFIG->company);
                        $SMARTY->assign('COMPANY', json_decode($COMP, true));
                        $body= $SMARTY->fetch('email-reset-password.tpl');
                        $to = $_POST["email"];
                        $from = (string) $CONFIG->company->name;
                        $fromEmail = (string) $CONFIG->company->email_from;
                        $subject = 'Forgotten password for Ready Steady Go Kids account - administration area';
                        if (sendMail($to, $from, $fromEmail, $subject, $body)) {
                            $result = true;
                        } else {
                            $error = '发送邮件时出错，请稍后再试。';
                        }
                    } catch (Exception $e) {
                        $error = $e;
                    }
                } else {
                    $error = '数据库错误，请稍后再试。';
                }
            }
            break;
    }
}

echo json_encode(array(
        'error'=>$error,
        'success'=>$result,
        'redirect'=>$redirect
));
